<style scoped="scoped">
  .title {
    font-weight: 600; font-size: 18px; line-height: 50px;
  }
  .checkbox {
    margin-left: 0px; margin-right: 20px;
  }
</style>
<template>
  <el-row>
    <Portlet :title="isEdit ? '修改线路' : '新增线路'">
      <el-form ref="elForm" class="el-form-col" label-width="120px" :model="model" label-position="left">
        <el-col :span="24">
          <el-row :gutter="15">
            <el-col :md="12" :lg="12" :xl="12">
              <span class="title">线路起点-揽货</span>
              <el-row :gutter="15">
                <el-col :span="19">
                  <el-form-item prop="startAddressArr" label="线路起点" :rules="[
                    {required: true, message: '线路起点必须', trigger: 'change'}
                  ]">
                    <Cascade-address changeOnSelect v-model="model.startAddressArr" :level="2" placeholder="请选择" disabled></Cascade-address>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-button type="primary" @click.prevent="showWarehouse" v-if="!isEdit">选择收货仓</el-button>
                </el-col>
                <el-col :span="10">
                  <el-form-item prop="startDistrictNo" label="" :rules="[
                  ]">
                    <el-select v-model="model.startDistrictNo" clearable placeholder="请选择区" :disabled="true">
                      <el-option v-for="item in startDistrictArr"
                                 :key="item.areaNo"
                                 :label="item.areaName"
                                 :value="item.areaNo">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item prop="startAddress" label="详细地址：">
                    <el-input v-model="model.startAddress" placeholder="" clearable :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="startCoverageAreaNo" label="揽货覆盖范围" :rules="[
                    {required: true, message: '揽货覆盖范围必须', trigger: 'blur'}
                  ]">
                    <el-checkbox :indeterminate="isIndeterminateStart"
                                 v-model="checkAllStart"
                                 @change="handleCheckAllChangeStart"
                                 v-if="startDistrictArr.length"
                                 :disabled="isEdit"
                    >全选</el-checkbox>
                    <el-checkbox-group :disabled="isEdit" v-model="model.startCoverageAreaNo" @change="handleCheckedCitiesChangeStart">
                      <el-checkbox class="checkbox" v-for="item of startDistrictArr" :label="item.areaNo" :key="item.areaNo">{{item.areaName}}</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="solicitationName" label="揽货联系人" :rules="[
                    {required: true, message: '揽货联系人必须', trigger: 'blur'}
                  ]">
                    <el-input v-model="model.solicitationName" placeholder="" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="solicitationPhone" label="揽货联系电话" :rules="[
                    {required: true, message: '揽货联系电话必须', trigger: 'blur'},
                    {validator: isPhone, message: '电话格式不正确', trigger: 'blur'},
                  ]">
                    <el-input v-model="model.solicitationPhone" placeholder="" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :md="12" :lg="12" :xl="12">
              <span class="title">线路终点-到件</span>
              <el-row :gutter="15">
                <el-col :span="24">
                  <el-form-item prop="endAddressArr" label="线路终点：" :rules="[
                    {required: true, message: '线路终点必须', trigger: 'change'}
                  ]">
                    <Cascade-address changeOnSelect v-model="model.endAddressArr" :level="2" placeholder="请选择省市" :disabled="isEdit"></Cascade-address>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item prop="endDistrictNo" label="" :rules="[
                    {required: true, message: '线路终点必须', trigger: 'blur'},
                  ]">
                    <el-select v-model="model.endDistrictNo" clearable placeholder="请选择区" :disabled="isEdit">
                      <el-option v-for="item in endDistrictArr"
                                 :key="item.areaNo"
                                 :label="item.areaName"
                                 :value="item.areaNo">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item prop="endAddress" label="详细地址:">
                    <el-input v-model="model.endAddress" placeholder="" clearable :disabled="isEdit"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="endCoverageAreaNo" label="到件覆盖范围：" :rules="[
                    {required: true, message: '到件覆盖范围必须', trigger: 'blur'}
                  ]">
                    <el-checkbox :indeterminate="isIndeterminateEnd"
                                 v-model="checkAllEnd"
                                 @change="handleCheckAllChangeEnd"
                                 v-if="endDistrictArr.length"
                                 :disabled="isEdit"
                    >全选</el-checkbox>
                    <el-checkbox-group :disabled="isEdit" v-model="model.endCoverageAreaNo" @change="handleCheckedCitiesChangeEnd">
                      <el-checkbox class="checkbox" v-for="item of endDistrictArr" :label="item.areaNo" :key="item.areaNo">{{item.areaName}}</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="arrivalName" label="到件联系人：" :rules="[
                    {required: true, message: '到件联系人必须', trigger: 'blur'}
                  ]">
                    <el-input v-model="model.arrivalName" placeholder="" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="arrivalPhone" label="到件联系电话：" :rules="[
                    {required: true, message: '到件联系电话必须', trigger: 'blur'},
                    {validator: isPhone, message: '电话格式不正确', trigger: 'blur'},
                  ]">
                    <el-input v-model="model.arrivalPhone" placeholder="" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :md="24" :lg="24" :xl="24">
              <span class="title">时效及状态</span>
                <el-row :gutter="15">
                  <el-col :md="12" :lg="8" :xl="6">
                    <el-form-item label="承诺时效：" prop="aging" :rules="[
                    {required: true, message: '承诺时效必须', trigger: 'blur'},
                    {validator: isInteger, message: '承诺时效必须是整数', type:'array', trigger: 'blur'}
                  ]">
                      <el-input v-model="model.aging">
                        <template slot="append">天</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :md="12" :lg="8" :xl="6">
                    <el-form-item label="线路状态：" prop="lineState" :rules="[
                    {required: true, message: '线路状态必须', trigger: 'blur'}
                  ]">
                      <el-radio-group v-model="model.lineState">
                        <el-radio :label="1" border>运营中</el-radio>
                        <el-radio :label="0" border>已停运</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
            </el-col>
            <el-col :md="24" :lg="24" :xl="24">
            <span class="title">线路价格</span>
              <el-row :gutter="15">
                <el-col :md="12" :lg="8" :xl="6">
                  <el-form-item label="起步价：" prop="startingPrice" :rules="[
                  {required: true, message: '起步价必须', trigger: 'blur'},
                  {validator: isFormatNumber, int: 9,  message: '起步价必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                ]">
                    <el-input v-model="model.startingPrice">
                      <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :md="12" :lg="8" :xl="6">
                  <el-form-item label="轻货单价：" prop="lightPrice" :rules="[
                  {required: true, message: '轻货单价必须', trigger: 'blur'},
                  {validator: isFormatNumber, int: 9,  message: '单价必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                ]">
                    <el-input v-model="model.lightPrice">
                      <template slot="append">元/m³</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :md="12" :lg="8" :xl="6">
                  <el-form-item label="重货单价：" prop="heavyPrice" :rules="[
                  {required: true, message: '重货单价必须', trigger: 'blur'},
                  {validator: isFormatNumber, int: 9,  message: '单价必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                ]">
                    <el-input v-model="model.heavyPrice">
                      <template slot="append">元/KG</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
          </el-col>
          </el-row>
        </el-col>
      </el-form>
    </Portlet>
    <Portlet>
      <el-row class="row">
        <el-col :span="24" class="text-center">
          <el-button :loading="loading" @click.prevent="cancel" type="primary">取消</el-button>
          <el-button :loading="loading" @click.prevent="submit(1)" type="primary" v-if="!isEdit">提交并继续创建</el-button>
          <el-button :loading="loading" @click.prevent="submit(0)" type="primary">提交</el-button>
        </el-col>
      </el-row>
    </Portlet>
    <select-warehouse-modal ref="selectWarehouseModal" @value="getWarehouse"></select-warehouse-modal>
  </el-row>
</template>

<script>
import {isEqual, copy, dotData} from '@/utils'
import {isFormatNumber, isPhone, isInteger} from '@/utils/validate'
import SelectWarehouseModal from '@/views/oms/trunkLine/SelectWarehouseModal'
export default {
  components: {
    SelectWarehouseModal
  },
  filters: {
  },
  data() {
    return {
      id: this.$route.query.id,
      loading: false,
      isIndeterminateStart: false,
      isIndeterminateEnd: false,
      checkAllStart: false,
      checkAllEnd: false,
      startDistrictArr: [],
      endDistrictArr: [],
      model: {
        startAddressArr: [],
        startDistrictNo: '',
        startAddress: '',
        startCoverageAreaNo: [],
        solicitationName: '',
        solicitationPhone: '',
        endAddressArr: [],
        endDistrictNo: '',
        endAddress: '',
        endCoverageAreaNo: [],
        arrivalName: '',
        arrivalPhone: '',
        aging: '',
        lineState: 1,
        startingPrice: '',
        lightPrice: '',
        heavyPrice: ''
      },
      warehouse: {},
      trunkLineDetail: {},
      isEdit: false
    }
  },
  watch: {
    'model.startAddressArr'(val, oldVal) {
      if (isEqual(val, oldVal) || val.length !== 2) {
        return
      }
      if (!this.isEdit) {
        this.model.startDistrictNo = ''
        this.checkAllStart = false
        this.startDistrictArr = []
      }
      this.getStartDistrictStart(val[1])
    },
    'model.endAddressArr'(val, oldVal) {
      if (isEqual(val, oldVal) || val.length !== 2) {
        return
      }
      if (!this.isEdit) {
        this.model.endDistrictNo = ''
        this.checkAllEnd = false
        this.endDistrictArr = []
      }
      this.getStartDistrictEnd(val[1])
    }
  },
  computed: {
  },
  created() {
    if (this.id) {
      // 修改
      this.isEdit = true
      // 获取线路详情
      this.getDetail()
    } else {
      // 新增
      this.isEdit = false
      // 获取用户仓库
      this.getWarehouseList()
      // 获取默认仓库
      this.getDefaultWarehouse()
    }
  },
  methods: {
    isFormatNumber,
    isPhone,
    isInteger,
    handleCheckAllChangeStart(val) {
      if (val) {
        this.model.startCoverageAreaNo = []
        this.startDistrictArr.forEach(item => {
          this.model.startCoverageAreaNo.push(item.areaNo)
        })
      } else {
        this.model.startCoverageAreaNo = []
      }
    },
    handleCheckAllChangeEnd(val) {
      if (val) {
        this.model.endCoverageAreaNo = []
        this.endDistrictArr.forEach(item => {
          this.model.endCoverageAreaNo.push(item.areaNo)
        })
      } else {
        this.model.endCoverageAreaNo = []
      }
    },
    handleCheckedCitiesChangeStart(value) {
      if (this.startDistrictArr.length === value.length) {
        this.checkAllStart = true
      } else {
        this.checkAllStart = false
      }
    },
    handleCheckedCitiesChangeEnd(value) {
      if (this.endDistrictArr.length === value.length) {
        this.checkAllEnd = true
      } else {
        this.checkAllEnd = false
      }
    },
    getStartDistrictStart(val) {
      this.$ajax.get('/ms-address/address/findByParentNo', {parentNo: val}).then(response => {
        this.startDistrictArr = response.data || []
      })
    },
    getStartDistrictEnd(val) {
      this.$ajax.get('/ms-address/address/findByParentNo', {parentNo: val}).then(response => {
        this.endDistrictArr = response.data || []
      })
    },
    // 获取线路详情
    getDetail() {
      this.$ajax.get('/ms-warehouse-trunk/line/get-trunk-line', {id: this.id}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data') || {}
          let startAddressArr = []
          startAddressArr.push(dotData(response, 'data.startProvinceNo'))
          startAddressArr.push(dotData(response, 'data.startCityNo'))
          data.startAddressArr = startAddressArr
          let endAddressArr = []
          endAddressArr.push(dotData(response, 'data.endProvinceNo'))
          endAddressArr.push(dotData(response, 'data.endCityNo'))
          data.endAddressArr = endAddressArr
          data.startCoverageAreaNo = data.startCoverageAreaNo.split(',')
          data.endCoverageAreaNo = data.endCoverageAreaNo.split(',')
          this.model = data
        }
      })
    },
    // 读取用户是否存在仓库
    getWarehouseList() {
      this.$ajax.get('/ms-warehouse-order/ch-warehouse-manager/getJHBWarehouseList').then(response => {
        const success = dotData(response, 'success')
        let warehouseList = []
        if (success) {
          warehouseList = dotData(response, 'data') || []
        }
        if (warehouseList.length < 1) {
          this.$confirm('未找到您的收货仓信息，请先新建收货仓！', '异常提示', {
            type: 'success',
            confirmButtonText: '确定',
            showCancelButton: true,
            closeOnClickModal: false
          }).then(_ => {
            this.$router.push({path: '/redirect/ss-oms/warehouse/configuration/index'})
          })
        }
      })
    },
    // 读取默认仓库
    getDefaultWarehouse() {
      this.$ajax.get('/ms-warehouse-order/ch-warehouse-manager/getDefaultWarehouse').then(response => {
        let data = dotData(response, 'data')
        if (data) {
          this.model.startAddressArr = []
          this.warehouse = dotData(response, 'data') || {}
          this.model.startAddressArr.push(dotData(response, 'data.houseProvinceNo'))
          this.model.startAddressArr.push(dotData(response, 'data.houseCityNo'))
          this.getStartDistrictStart(dotData(response, 'data.houseCityNo'))
          this.model.startDistrictNo = dotData(response, 'data.houseDistrictNo')
          this.model.startAddress = dotData(response, 'data.houseAddress')
          this.model.startCoverageAreaNo = dotData(response, 'data.coverageAreaNo').split(',')
        }
      })
    },
    // 选择仓库
    showWarehouse() {
      this.$refs.selectWarehouseModal.show()
    },
    // 获取选择仓库
    getWarehouse(val) {
      console.log(val)
      this.warehouse = val || {}
      this.model.startAddressArr.push(dotData(val, 'houseProvinceNo'))
      this.model.startAddressArr.push(dotData(val, 'houseCityNo'))
      this.getStartDistrictStart(dotData(val, 'houseCityNo'))
      this.model.startDistrictNo = dotData(val, 'houseDistrictNo')
      this.model.startAddress = dotData(val, 'houseAddress')
      this.model.startCoverageAreaNo = dotData(val, 'coverageAreaNo').split(',')
    },
    // 提交
    submit(again) {
      this.$refs.elForm.validate(result => {
        if (!result) {
          return
        }
        let postUrl = ''
        let postData = {}
        let postPrompt = ''
        if (this.isEdit) {
          // 修改
          postPrompt = '修改'
          postUrl = '/ms-warehouse-trunk/line/update-line'
          postData = {
            id: this.id,
            solicitationName: this.model.solicitationName,
            solicitationPhone: this.model.solicitationPhone,
            arrivalName: this.model.arrivalName,
            arrivalPhone: this.model.arrivalPhone,
            aging: this.model.aging,
            startingPrice: this.model.startingPrice,
            lightPrice: this.model.lightPrice,
            heavyPrice: this.model.heavyPrice,
            lineState: this.model.lineState
          }
        } else {
          // 新增
          postPrompt = '新增'
          postUrl = '/ms-warehouse-trunk/line/add-line'
          postData = copy(this.model, true)
          postData.warehouseId = this.warehouse.id
          postData.startProvinceNo = dotData(postData, 'startAddressArr[0]') || ''
          postData.startCityNo = dotData(postData, 'startAddressArr[1]') || ''
          delete postData.startAddressArr
          postData.endProvinceNo = dotData(postData, 'endAddressArr[0]') || ''
          postData.endCityNo = dotData(postData, 'endAddressArr[1]') || ''
          delete postData.endAddressArr
          postData.startCoverageAreaNo = postData.startCoverageAreaNo.join(',')
          postData.endCoverageAreaNo = postData.endCoverageAreaNo.join(',')
        }
        // 提交
        this.loading = true
        this.$ajax.post(postUrl, postData).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.$confirm(postPrompt + '成功', '温馨提示', {
              type: 'success',
              center: true,
              confirmButtonText: '确定',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              if (again) {
                if (this.$refs.elForm) {
                  this.$refs.elForm.resetFields()
                  this.getDefaultWarehouse()
                }
              } else {
                this.$router.push({path: '/redirect/ss-oms/trunkLine/index'})
              }
            })
          }
          this.loading = false
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    cancel() {
      this.$router.push({path: '/redirect/ss-oms/trunkLine/index'})
    }
  }
}
</script>
